import React, { useEffect } from 'react';
import Scroll from '../../baseUI/scroll';
import { connect } from 'react-redux';
import { filterIdx, filterIndex } from '../../api/utils';
import { getRankList } from './store';
import { Container, List, ListItem, SongList } from './style';
import { EnterLoading } from './style';
import Loading from '../../baseUI/Loading';

function Rank(props) {
  const { rankList: list, loading } = props;
  const { getRankListDataDispatch } = props;

  
  let rankList = list ? list.toJS() : [];
  let globalStartIndex = filterIndex(rankList);
  let officialList = rankList.slice(0, globalStartIndex);
  let globalList = rankList.slice(globalStartIndex);

  useEffect(() => {
    getRankListDataDispatch();
  }, []);


  const enterDetail = (name) => {
    const idx = filterIdx(name);
    if(idx === null) {
      alert('暂无相关数据');
      return;
    }
  };

  const renderSongList = (list) => {
    return list.length ? (
      <SongList>
        {
          list.map((item, index) => {
            return <li key={index}>{index + 1}. {item.first} - {item.second}</li>;
          })
        }
      </SongList>
    ) : null;
  };

  const renderRankList = (list, global) => {
    return (
      <List globalRank={global}>
        {
          list.map((item) => {
            return (
              <ListItem key={item.id} tracks={item.tracks} onClick={() => enterDetail(item.name)}>
                <div className="img_wrapper">
                  <img src={item.coverImgUrl} alt=""/>
                  <div className="decorate"></div>
                  <span className="update_frequecy">{item.updateFrequency}</span>
                </div>
                { renderSongList(item.tracks) }
              </ListItem>
            );
          })
        }
      </List>
    );
  };

  let displayStyle = loading ? { display: 'none' } : { display: '' };

  return (
    <Container>
      <Scroll>
        <div>
          <h1 className="offical" style={displayStyle}>官方榜</h1>
          { renderRankList(officialList) }
          <h1 className="global" style={displayStyle}>全球榜</h1>
          { renderRankList(globalList, true) }
          { loading ? <EnterLoading><Loading></Loading></EnterLoading> : null }
        </div>
      </Scroll>
    </Container>
  );
}

const mapStateToProps = (state) => ({
  rankList: state.rank.get('rankList'),
  loading: state.rank.get('loading')
});

const mapDispatchToProps = (dispatch) => {
  return {
    getRankListDataDispatch() {
      dispatch(getRankList());
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(React.memo(Rank));